const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const { Worker } = require('worker_threads')

router.prefix('/hamsterkombat')

router.get("/accounts", async (ctx, next) => {
    const conn = ctx.state.sqlconn;
    const [result, fields] = await conn.query("select * from hamsterkombat")
    ctx.body = {
        code: 200,
        msg: 'ok',
        data: result
    }
})


router.post('/token', async (ctx, next) => {
    const conn = ctx.state.sqlconn;
    const body = ctx.request.body;
    const identifier = body.identifier;
    try {
        const result = await conn.query(`insert into hamsterkombat 
            (identifier, token, proxy) 
            values (?, ?, ?)
            on duplicate key
            update token=?, proxy=?`,
            [identifier, body.token, body.proxy, body.token, body.proxy])
        ctx.body = {
            code: 200,
            msg: 'ok'
        }
    } catch (error) {
        console.error(error)
        ctx.body = {
            code: -1,
            msg: error.toString(),
            data: error
        }
    }
})

router.get('/token', async (ctx, next) => {
    const conn = ctx.state.sqlconn;
    const [results, fields] = await conn.query('select * from hamsterkombat where id>0')
    ctx.body = {
        code: 200,
        msg: 'ok',
        data: results
    }
})

router.post('/excute', async (ctx, next) => {
    const excutor = HamsterkombatExcutor.shared()
    excutor.start()
    ctx.body = {
        code: 200,
        msg: 'ok',
        data: excutor.isRunning()
    }
})

router.get('/excute', async (ctx, next) => {
    const excutor = HamsterkombatExcutor.shared()
    ctx.body = {
        code: 200,
        msg: 'ok',
        data: excutor.isRunning()
    }
})

module.exports = router


// worker thread
class HamsterkombatExcutor {
    constructor() { }

    static shared() {
        if (!HamsterkombatExcutor.instance) {
            HamsterkombatExcutor.instance = new HamsterkombatExcutor();
        }
        return HamsterkombatExcutor.instance;
    }

    start() {
        if (this.worker != null) {
            return;
        }
        const worker = new Worker("./worker/hamsterkombat.js", {
            workerData: "hello world"
        });
        // worker.on('message', (msg) => {
        //     console.log(msg)
        // });
        worker.on('error', (error) => {
            console.error(error)
        });
        worker.on('exit', (code) => {
            console.log("worker exit: ", code)
            this.worker = null
        });
        this.worker = worker
    }

    stop() {
        if (this.worker != null) {
            this.worker.terminate()
        }
    }

    isRunning() {
        return this.worker != null
    }
}